#include "xor.h"

/**
 * @brief xor 计算
 * 
 * @param pKeyValue - 密钥
 * @param KeyLength - 密钥长度
 * @param pDataIn   - 数据流
 * @param DataSize  - 数据长度
 */
static void XorCalculate(uint8_t *pKeyIn, uint8_t KeyLength, uint8_t *pDataIn, uint32_t DataSize);

static void XorCalculate(uint8_t *pKeyIn, uint8_t KeyLength, uint8_t *pDataIn, uint32_t DataSize)
{
  uint32_t CodeOffset = 0;

  if ((pKeyIn != NULL) && (pDataIn != NULL) && (DataSize != 0))
  {
    if ((KeyLength > 0) && (KeyLength <= ENCRYPTION_KEY_LENGTH))
    {
      for (uint32_t i = 0; i < DataSize; i++)
      {
        if (CodeOffset >= KeyLength)
        {
          CodeOffset = 0;
        }

        pDataIn[i] = pDataIn[i] ^ pKeyIn[CodeOffset++];
      }
    }
  }
}

void XorEncryptCalculate(uint8_t *pKeyIn, uint8_t KeyLength, uint8_t *pDataPacket, uint32_t DataSize)
{
  XorCalculate(pKeyIn, KeyLength, pDataPacket, DataSize);
}

void XorDecryptCalculate(uint8_t *pKeyIn, uint8_t KeyLength, uint8_t *pDataPacket, uint32_t DataSize)
{
  XorCalculate(pKeyIn, KeyLength, pDataPacket, DataSize);
}
